 // 工具函数和通用方法

// 处理规则表单提交
document.addEventListener('DOMContentLoaded', function() {
    const ruleForm = document.getElementById('rule-form');
    if (ruleForm) {
        ruleForm.addEventListener('submit', handleRuleFormSubmit);
    }
});

async function handleRuleFormSubmit(e) {
    e.preventDefault();
    
    const formData = new FormData(e.target);
    const ruleType = formData.get('rule_type');
    
    const rule = {
        pattern: formData.get('pattern'),
        pattern_type: formData.get('pattern_type') || 'string',
        enabled: formData.get('enabled') === 'true'
    };
    
    if (ruleType === 'mock') {
        // Mock规则
        rule.type = 'mock';
        rule.mock_response = {
            status: parseInt(formData.get('mock_status')) || 200,
            content_type: formData.get('mock_content_type')
        };
        
        // 处理Mock数据源
        if (formData.get('mock_data_source') === 'file') {
            rule.mock_response.content_file = formData.get('mock_content_file');
        } else {
            rule.mock_response.content = formData.get('mock_content');
        }
        
        // 处理自定义头部
        const mockHeaders = formData.get('mock_headers');
        if (mockHeaders && mockHeaders.trim()) {
            try {
                rule.mock_response.headers = JSON.parse(mockHeaders);
            } catch (error) {
                alert('自定义响应头格式错误，请检查JSON格式');
                return;
            }
        }
    } else {
        // 代理规则
        rule.target = {
            scheme: formData.get('scheme'),
            host: formData.get('host'),
            port: parseInt(formData.get('port'))
        };
        
        if (formData.get('strip_prefix')) {
            rule.strip_prefix = formData.get('strip_prefix');
        }
    }
    
    try {
        let response;
        if (currentEditIndex >= 0) {
            response = await fetch(`/api/rules/${currentEditIndex}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(rule)
            });
        } else {
            response = await fetch('/api/rules', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(rule)
            });
        }
        
        if (response.ok) {
            hideRuleModal();
            loadRules();
        } else {
            const errorData = await response.json();
            alert('保存失败: ' + (errorData.error || '未知错误'));
        }
    } catch (error) {
        console.error('保存失败:', error);
        alert('保存失败: ' + error.message);
    }
}

// 格式化时间戳
function formatTimestamp(timestamp) {
    if (!timestamp) return '';
    
    try {
        const date = new Date(timestamp);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    } catch (error) {
        return timestamp;
    }
}

// 验证URL格式
function isValidUrl(string) {
    try {
        new URL(string);
        return true;
    } catch (_) {
        return false;
    }
}

// 验证端口号
function isValidPort(port) {
    const portNum = parseInt(port);
    return !isNaN(portNum) && portNum >= 1 && portNum <= 65535;
}

// 验证JSON格式
function isValidJson(jsonString) {
    try {
        JSON.parse(jsonString);
        return true;
    } catch (error) {
        return false;
    }
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    }
}

// 显示加载状态
function showLoading(elementId, message = '加载中...') {
    const element = document.getElementById(elementId);
    if (element) {
        element.innerHTML = `<div class="loading">${message}</div>`;
    }
}

// 隐藏加载状态
function hideLoading(elementId) {
    const element = document.getElementById(elementId);
    if (element) {
        element.innerHTML = '';
    }
}

// 显示错误消息
function showError(message, duration = 3000) {
    const errorEl = document.createElement('div');
    errorEl.className = 'alert error';
    errorEl.textContent = message;
    errorEl.style.position = 'fixed';
    errorEl.style.top = '20px';
    errorEl.style.right = '20px';
    errorEl.style.zIndex = '9999';
    
    document.body.appendChild(errorEl);
    
    setTimeout(() => {
        if (errorEl.parentNode) {
            errorEl.parentNode.removeChild(errorEl);
        }
    }, duration);
}

// 显示成功消息
function showSuccess(message, duration = 3000) {
    const successEl = document.createElement('div');
    successEl.className = 'alert success';
    successEl.textContent = message;
    successEl.style.position = 'fixed';
    successEl.style.top = '20px';
    successEl.style.right = '20px';
    successEl.style.zIndex = '9999';
    
    document.body.appendChild(successEl);
    
    setTimeout(() => {
        if (successEl.parentNode) {
            successEl.parentNode.removeChild(successEl);
        }
    }, duration);
}